import {ref} from "vue";
import {BaseURL} from "../../utils/lshttp";
import {submitFeedbackAPI} from "../../services/me";
import {conUtils} from "../../utils/conUtils";
import {requestAndroidPermission} from "../../js_sdk/wa-permission/permission";

export const useAddFeedback = () => {
    // 问题列表
    const listType = ref(['订单问题', '餐品问题', '商家问题', '程序BUG', '售后问题', '其他反馈'])
    // 上传的图片地址列表
    const images = ref([])
    // 选择的问题下标
    const currentIndex = ref(0)
    // 选择的问题订单
    const order_no = ref("")
    // 提交数据源
    const formData = {type: 1, content: '', phone: '', link_order: "", imgs: []}
    // 最大图片数量
    const countImg = ref(5)
    // 选择问题类型
    const chooseType = (index) => {
        currentIndex.value = index
        formData.type = index + 1
    }
    // 跳转订单选择页面
    const toChooseOrder = () => {
        uni.navigateTo({
            url: 'chooseorder',
            events: {
                // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                acceptDataFromOpenedPage: function (data) {
                    order_no.value = data.data.order_no + ""
                    formData.link_order = data.data.order_no + ""
                    console.log(data)
                }
            }
        })
    }
    // 跳转问题反馈列表页面
    const toFeedbackList = () => {
        uni.navigateTo({url: 'feedback',})
    }
    // 选择图片
    const chooseImages = () => {
        uni.chooseImage({
            count: countImg.value - images.value.length,
            sizeType: ['original', 'compressed'],
            // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album'],
            // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                console.log("chooseImage", res.tempFilePaths)
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                res.tempFilePaths.forEach((item) => {
                    images.value.push(item)
                })
                console.log("images", images.value)
            }
        });
    }
    // 上传多长图片
    const uploadImages = () => {
        // 处理图片数据
        let imgs = images.value.map((value, index) => {
            return {
                name: "files[" + index + "]",
                uri: value
            }
        })
        console.log("imgs", imgs)
        uni.showLoading({
            title: '上传中'
        })
        uni.uploadFile({
            url: BaseURL + '/api/userFeedback/moreUpload',
            files: imgs,
            async success(res1) {
                console.log("/api/userFeedback/moreUpload", res1)
                formData.imgs = JSON.parse(res1.data).result[0]
                await submitFeedbackAPI(formData)
                await uni.showToast({title: '提交成功', icon: 'none'})
                await uni.navigateBack()
            }, fail(e) {
                uni.showToast({title: "上传失败" + e.toString(), icon: "none"})
            }, complete() {
                uni.hideLoading()
            }
        })
    }
    let imgs = []
    // 上传单张图片
    const uploadImage = (path) => {
        uni.uploadFile({
            url: BaseURL + '/api/userFeedback/singleUpload',
            method: 'POST',
            filePath: path,
            name: 'file',
            async success(res1) {
                console.log("res1", res1)
                console.log("res1", JSON.parse(res1.data).result[0])
                imgs.push(JSON.parse(res1.data).result[0])
                console.log("res1", imgs)
                if (imgs.length === images.value.length) {
                    formData.imgs = imgs
                    await submitFeedbackAPI(formData)
                    await uni.showToast({title: '提交成功', icon: 'none'})
                    await uni.navigateBack()
                }
            }, fail(error) {
                conUtils("error", error)
            }, complete() {
                uni.hideLoading()
            }
        })
    }
    // 验证并提交意见反馈
    const submitFeedBack = async () => {
        console.log("submitFeedBack", formData)
        if (!formData.content) {
            await uni.showToast({title: '请输入建议描述', icon: 'none'})
            return
        }
        if (!formData.phone || formData.phone.length !== 11) {
            await uni.showToast({title: '请输联系电话', icon: 'none'})
            return
        }
        if (!formData.link_order && (formData.type === 1 || formData.type === 2 || formData.type === 3 || formData.type === 5)) {
            await uni.showToast({title: '请输选择订单', icon: 'none'})
            return
        }
        console.log("images.length", images)
        if (!images || images.value.length === 0) {
            await uni.showToast({title: '请添加图片', icon: 'none'})
            return
        }
        // #ifdef MP
        images.value.forEach((item) => {
            uploadImage(item)
        })
        // #endif
        // #ifdef APP-PLUS || H5
        uploadImages()
        // #endif
    }
    const isYJJJ = ref(false)
    // 获取图片前需要获取是否有选择图片权限
    const getPermission = async () => {
        let platform = uni.getSystemInfoSync().platform
        if (platform === 'ios') {
            chooseImages()
            return
        }

        const photo = uni.getStorageSync("photo")
        if (photo) {
            chooseImages()
            return
        }
        uni.showModal({
            title: '提示',
            content: "修改头像需要获取您设备上的相册权限，是否同意授权？",
            confirmText: '同意授权',
            success: async function (res) {
                if (res.confirm) {
                    const result = await requestAndroidPermission("android.permission.READ_EXTERNAL_STORAGE")
                    if (result === 1) {
                        uni.setStorageSync("photo", true)
                        chooseImages()
                    } else if (result === 0) {
                        uni.setStorageSync('photo', false)
                    } else {
                        uni.setStorageSync('photo', false)
                        isYJJJ.value = true
                    }
                }
            }
        })
    }

    return {
        listType,
        images,
        currentIndex,
        order_no,
        formData,
        countImg,
        chooseType,
        toChooseOrder,
        toFeedbackList,
        chooseImages,
        uploadImages,
        uploadImage,
        submitFeedBack,
        getPermission
    }
}